'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken')

class HomeController extends Controller {


    //登录
    async login() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body

        // const data = await app.mysql.get("login", {
        //     username,
        //     password
        // })

        const data = await app.mysql.query(`select * from login where username = "${username}" and password = "${password}"`)
        // console.log(data)
        const datas = data.map(item => {
            return {

                name: item.name,
                id: item.id,
                username: item.username,
                img: item.img,
                admin: item.admin,
            }
        })

        let token = jwt.sign({ ...data }, '1901A', { expiresIn: '20m' })

        if (data && username, password !== '') {
            ctx.body = {
                code: 1,
                datas,
                token,
                msg: '登录成功'
            }
        }
        else {
            ctx.body = {
                code: 0,
                msg: '账号密码有误"'
            }
        }

    }



    //注册
    async register() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body
        const data = await app.mysql.get("login", { username })
        if (!data && username, password !== '') {
            await app.mysql.insert("login", { username, password })
            ctx.body = {
                code: 1,
                // data,
                msg: '注册成功'
            }
        }
        else {
            ctx.body = {
                code: 0,
                // data,
                msg: "账号已存在或则为空"
            }
        }
    }





}

module.exports = HomeController;
